package com.spring.security.springsecuritydemo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 自定义实烦类，用于查询自己的数据库的用户
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private PasswordEncoder pw;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {


        System.out.println("进入到loadUserByUsername");
        //查询数据库是否存在

        if (!"admin".equals(userName))
        {
            //不存在抛出异常
            throw new UsernameNotFoundException("用户名不存在");
        }
        //密码进行解析
        String encode = pw.encode("123");
        //
        return new User(userName,encode, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,test,super"));
    }
}
